from django.shortcuts import render
from django.views import View
from booktest.models import BookInfo
from django import http
import json

"""
  | 功能         | 请求方式 | 请求路径    |
  | ------------ | -------- | ----------- |
  | 获取所有书籍 | get      | /books      |
  | 创建单本书籍 | post     | /books      |
  | 获取单本书籍 | get      | /books/{pk} |
  | 修改单本书籍 | put      | /books/{pk} |
  | 删除单本书籍 | delete   | /books/{pk} |
"""
# 1.获取所有书籍,创建单本书籍(列表视图)
class BookListView(View):
    def get(self, request):
        # 1.获取所有书籍
        books = BookInfo.objects.all()

        # 2.将书籍对象列表,转成字典列表
        book_list = []
        for book in books:
            book_dict = {
                "id": book.id,
                "btitle": book.btitle,
                "bpub_date": book.bpub_date,
                "bread": book.bread,
                "bcomment": book.bcomment,
            }
            book_list.append(book_dict)

        # 3.返回响应,safe=False可以转换非字典数据
        return http.JsonResponse(book_list,safe=False)

    def post(self,request):
        # 1.获取参数
        dict_data = json.loads(request.body.decode())
        btitle = dict_data.get("btitle")
        bpub_date = dict_data.get("bpub_date")
        bread = dict_data.get("bread")
        bcomment = dict_data.get("bcomment")

        # 2.校验参数(省略)
        # 3.数据入库
        book = BookInfo.objects.create(**dict_data)

        book_dict = {
            "id": book.id,
            "btitle": book.btitle,
            "bpub_date": book.bpub_date,
            "bread": book.bread,
            "bcomment": book.bcomment,
        }
        # 4,返回响应
        return http.JsonResponse(book_dict, status=201)


# 2.获取单本书籍,修改单本书籍,删除单本书籍(详情视图)
class BookDetailView(View):
    def get(self, request, pk):
        # 1.获取数据
        book = BookInfo.objects.get(pk=pk)

        # 2.数据转换
        book_dict = {
            "id": book.id,
            "btitle": book.btitle,
            "bpub_date": book.bpub_date,
            "bread": book.bread,
            "bcomment": book.bcomment,

        }
        # 3.返回响应
        return http.JsonResponse(book_dict)

    def put(self, request, pk):
        # 1.获取参数
        dict_data = json.loads(request.body.decode())

        # 2,校验数据(省略)
        # 3,数据入库
        BookInfo.objects.filter(pk=pk).update(**dict_data)
        book = BookInfo.objects.get(pk=pk)

        book_dict = {
            "id": book.id,
            "btitle": book.btitle,
            "bpub_date": book.bpub_date,
            "bread": book.bread,
            "bcomment": book.bcomment,
        }

        # 4,返回响应
        return http.JsonResponse(book_dict, status=201)

    def delete(self, request, pk):
        # 1.获取数据
        book = BookInfo.objects.get(pk=pk)

        # 2.删除数据
        book.delete()

        # 3.返回响应
        return http.HttpResponse(status=204)